//
//  syncDataService.m
//  APJ Resource
//
//  Created by Richard Zhao on 1/27/14.
//  Copyright (c) 2014 APJ. All rights reserved.
//

#import "syncDataService.h"
#import "HRStore.h"
#import "webService.h"
#import "Const.h"
#import "Encrypt.h"
#import "SSZipArchive.h"

@implementation syncDataService
{
    NSDictionary *tableMapping;
    NSDictionary *tableKeys;
}
+ (syncDataService *)sharedService
{
    static syncDataService *sharedService;
    if (!sharedService) {
        sharedService = [[super allocWithZone:nil] init];
        sharedService->tableMapping =
            [NSDictionary dictionaryWithObjectsAndKeys:
              @"dbo.UserAccountView",       @"User"
             ,@"HR.DeptMaster",             @"Dept"                    
             ,@"HR.EducationBackground",    @"EducationBackground"
             ,@"HR.Interview",              @"Interview"
             ,@"HR.InterviewSkillMatrix",   @"InterviewSkillMatrix"  
             ,@"HR.Qualification",          @"Qualification"        
             ,@"HR.ResourceReqSkillMatrix", @"ResourceReqSkillMatrix"
             ,@"HR.ResourceRequirement",    @"ResourceRequirement"   
             ,@"HR.Skill",                  @"Skill"                  
             ,@"HR.SkillCategory",          @"SkillCategory"           
             ,@"HR.StaffMaster",            @"Staff"               
             ,@"HR.StaffSkillMatrix",       @"StaffSkillMatrix"        
             ,@"HR.WorkExperience",         @"WorkExperience"          
             ,@"PM.ProjectAllocation",      @"ProjectAllocation"      
             ,@"PM.ProjectMaster",          @"Project"              
             ,nil];

        sharedService->tableKeys =
        [NSDictionary dictionaryWithObjectsAndKeys:
          [NSArray arrayWithObject:@"Id"],                              @"User"
         ,[NSArray arrayWithObject:@"DeptId"],                          @"Dept"
         ,[NSArray arrayWithObject:@"Id"],                              @"EducationBackground"
         ,[NSArray arrayWithObject:@"InterviewId"],                     @"Interview"
         ,[NSArray arrayWithObjects:@"InterviewId", @"SkillCode", nil], @"InterviewSkillMatrix"
         ,[NSArray arrayWithObject:@"Id"],                              @"Qualification"
         ,[NSArray arrayWithObjects:@"ReqId", @"SkillCode", nil],       @"ResourceReqSkillMatrix"
         ,[NSArray arrayWithObject:@"ReqId"],                           @"ResourceRequirement"
         ,[NSArray arrayWithObject:@"SkillCode"],                       @"Skill"
         ,[NSArray arrayWithObject:@"SkillCategoryCode"],               @"SkillCategory"
         ,[NSArray arrayWithObject:@"StaffId"],                         @"Staff"
         ,[NSArray arrayWithObjects:@"StaffId", @"SkillCode", nil],     @"StaffSkillMatrix"
         ,[NSArray arrayWithObject:@"Id"],                              @"WorkExperience"
         ,[NSArray arrayWithObject:@"Id"],                              @"ProjectAllocation"
         ,[NSArray arrayWithObject:@"ProjectId"],                       @"Project"
         ,nil];
    }
    
    return sharedService;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [self sharedService];
}

- (BOOL)doSyncDataFromWebService
{
    NSTimeInterval syncTimestamp = [[NSUserDefaults standardUserDefaults] doubleForKey:SYNC_TIMESTAMP_KEY];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [format stringFromDate:[NSDate dateWithTimeIntervalSince1970:syncTimestamp]];
    NSDate *newTimestamp = [NSDate date];
    
    id json = nil;
    for (NSString *key in [tableMapping allKeys]) {
        NSLog(@"%@", [tableMapping objectForKey:key]);
        json = [webService pullUpdatedDataFromTable:[tableMapping objectForKey:key]
                                        withColumns:@"*"
                                          startFrom:dateString];
        NSLog(@"%@", json);
        [[HRStore sharedStore] syncTable:key
                                withData:(NSArray *)[json objectForKey:@"Table"]
                                  byKeys:[tableKeys objectForKey:key]];
        
    }
    
    id data = [webService downloadFileSince:dateString];
    [self writeFile:data fileName:PHOTOS_FILE_NAME];
    [self unzip:PHOTOS_FILE_NAME];
    
    [[NSUserDefaults standardUserDefaults] setDouble:[newTimestamp timeIntervalSince1970]
                                              forKey:SYNC_TIMESTAMP_KEY];
    
    return YES;
}

- (void)writeFile:(NSString*)dataString fileName:(NSString*)fileName
{
    NSData *data = [Encrypt base64Decode:dataString];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:path atomically:YES];
}

- (void)unzip:(NSString *)zipFile
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:zipFile];
    
    [SSZipArchive unzipFileAtPath:path toDestination:documentsDirectory];
}

@end
